<script setup lang="ts">
import { Download } from '@element-plus/icons-vue'
import type {
  DatePickType,
  FormInstance,
} from 'element-plus'
import { defaultPagingParams, rules } from '../index'
import { PAGING } from '@/constant'
import type { EnergyBindItem } from '@/types'
import { energyApi } from '@/api'

const props = defineProps<{
  downloading: boolean
  disableDownload: boolean
  pointId: number
}>()
const emits = defineEmits<{
  search: []
  reset: []
  plus: []
  download: [params: any]
}>()
const query = defineModel({
  default: () => defaultPagingParams,
})
const [energyData, setEnergyData] = useState<
  EnergyBindItem[]
>([])
const searchFormRef = ref<FormInstance>()

const computedTime = computed({
  get() {
    return [query.value.startTime, query.value.endTime]
  },
  set([a, b]: any) {
    query.value.startTime = a
    query.value.endTime = b
  },
})
const computedTimeType = computed(() => {
  return ['datetimerange', 'daterange', 'monthrange'][
    +query.value.cycle - 1 || 0
  ] as DatePickType
})
const computedTimeFormat = computed(() => {
  return ['YYYY-MM-DD HH', 'YYYY-MM-DD', 'YYYY-MM'][
    +query.value.cycle - 1 || 0
  ] as string
})

async function search() {
  await searchFormRef.value?.validate()
  Object.assign(query.value, PAGING.PARAMS)
  await nextTick()
  emits('search')
}
async function getEnergyData() {
  const pointId = props.pointId
  if (!pointId) {
    setEnergyData([])
    return
  }
  const { data: res }
    = await energyApi.selectEnergy(props.pointId, query.value.containSub)
  setEnergyData(res)
}
function handleDisabledDate(date: Date) {
  const current = new Date()
  const t = date.getTime()
  return t > current.getTime()
  // return month !== targetMonth;
}
function handleDisabledHours() {
  const current = new Date()
  const hours = current.getHours()
  return [...range(hours, 24)]
}
function handleDisabledMinutes() {
  return [...range(0, 60)]
}

watchEffect(() => {
  const cycle = +unref(query).cycle
  switch (cycle) {
    case 1:
      computedTime.value = [
        dayjs().format('YYYY-MM-DD 00'),
        dayjs().format('YYYY-MM-DD 23'),
      ]
      break
    case 2:
      computedTime.value = [
        dayjs().format('YYYY-MM-DD'),
        dayjs().format('YYYY-MM-DD'),
      ]
      break
    case 3:
      computedTime.value = [
        dayjs().format('YYYY-MM'),
        dayjs().format('YYYY-MM'),
      ]
      break
  }
})

watch([
  () => props.pointId,
  () => query.value.containSub,
], async () => {
  await getEnergyData()
  // 重新获取能源品种后清空历史值
  query.value.energyCode = unref(energyData)[0]?.code
  emits('search')
})
// #endregion
</script>

<template>
  <el-form
    ref="searchFormRef"
    inline
    label-width="80px"
    label-position="left"
    :rules="rules"
    :model="query"
    class="flex-incompressible width-fill padding-bottom-xs relative"
  >
    <el-form-item>
      <ContainSubRadio v-model="query.containSub" />
    </el-form-item>
    <el-form-item label="能源品种" prop="energyCode">
      <ElSelect
        v-model="query.energyCode"
        :clearable="false"
        placeholder="请选择"
      >
        <ElOption
          v-for="item in energyData"
          :key="item.id"
          :value="item.code"
          :label="item.name"
        />
      </ElSelect>
    </el-form-item>
    <el-form-item label="采集时间" prop="cycle">
      <DictionaryPicker
        v-model="query.cycle"
        code="CHAO_BIAO_ZHOU_QI"
        :clearable="false"
      />
    </el-form-item>
    <el-form-item label="统计时间" prop="startTime">
      <ElDatePicker
        v-if="computedTimeType === 'datetimerange'"
        v-model="computedTime"
        type="datetimerange"
        :value-format="computedTimeFormat"
        :format="computedTimeFormat"
        :disabled-date="handleDisabledDate"
        :disabled-hours="handleDisabledHours"
        :disabled-minutes="handleDisabledMinutes"
        :clearable="false"
      />
      <ElDatePicker
        v-else
        v-model="computedTime"
        :type="computedTimeType"
        :value-format="computedTimeFormat"
        :format="computedTimeFormat"
        :disabled-date="handleDisabledDate"
        :disabled-hours="handleDisabledHours"
        :disabled-minutes="handleDisabledMinutes"
        :clearable="false"
      />
    </el-form-item>
    <el-form-item>
      <SearchButton @click="search" />
      <ElButton
        v-if="false"
        :loading="downloading"
        type="primary"
        :icon="downloading ? '' : Download"
        :disabled="disableDownload"
        @click="$emit('download', query)"
      >
        导出
      </ElButton>
    </el-form-item>
  </el-form>
</template>

<style lang="scss" scoped>
//------------------组件样式------------------
p {
  position: absolute;
  bottom: 4px;
  left: 0px;
  font-size: 14px;
  color: var(--el-text-color-secondary);
  // transform: translateY(100%);
}
//-------------样式穿透-------------
</style>
